﻿using System.Web.Mvc;
using System.Reflection;

using Microsoft.Practices.ServiceLocation;

using Castle.Windsor;
using Castle.MicroKernel.Registration;
using Castle.Windsor.Configuration.Interpreters;
using MvcCms.Service.Code.Membership;

namespace MvcCms.Web.Ioc
{
    public class ContainerBuilder
    {
        private static WindsorContainer _container;

        public static IWindsorContainer Build(string config)
        {
            _container = new WindsorContainer(new XmlInterpreter(config));

            BuildControllers();
            BuildServices();
            BuildRepositories();
            _container.Register(
                Component.For<IServiceLocator>().Instance(new WindsorServiceLocator(_container))
             );
            return _container;
        }
        private static void BuildControllers()
        {
            _container.Register(AllTypes.FromThisAssembly()
                                .BasedOn<IController>()
                                .If(t => t.Name.EndsWith("Controller"))
                                .Configure((c => c.LifeStyle.Transient)));
        }
        private static void BuildServices()
        {
            _container.Register(Component.For<MvcCmsMembershipProvider>()
                                .LifeStyle.Transient
                                .Named("MvcCmsMembershipProvider"));

            _container.Register(AllTypes.FromAssemblyNamed("MvcCms.Service")
                                .Where(type => type.Name.EndsWith("Service"))
                                .WithService.DefaultInterface()
                                .Configure(c => c.LifeStyle.Transient));

            _container.Register(AllTypes.FromAssemblyNamed("MvcCms.Data.Service")
                                .Where(type => type.Name.EndsWith("Service"))
                                .WithService.DefaultInterface()
                                .Configure(c => c.LifeStyle.Transient));

            _container.Register(AllTypes.FromAssemblyNamed("MvcCms.Data.Service")
                                .Where(type => type.Name.EndsWith("Repository"))
                                .WithService.DefaultInterface()
                                .Configure(c => c.LifeStyle.Transient));
        }
        private static void BuildRepositories()
        {
            _container.Register(AllTypes.FromAssemblyNamed("MvcCms.Data")
                                .Where(type => type.Name.EndsWith("Repository"))
                                .WithService.DefaultInterface()
                                .Configure(c => c.LifeStyle.Transient));
        }
    }
}
